package com.hugegreenbug.msoss;

import android.os.SystemClock;

public class ImageScheduler {
	private volatile Runnable mRunnable;
	private volatile Thread mThread;
	private volatile long mNextRun;
	private Runnable mScheduler;
	private Thread mSchedulerThread;
	private volatile boolean runScheduler;
	
	public ImageScheduler(Runnable run) {
		mNextRun = -1;
		mRunnable = run;
		runScheduler = true;
		mScheduler = new Runnable() {
			public void run() {
				scheduler();
			}
		};
		
		mSchedulerThread = new Thread(mScheduler);
		mSchedulerThread.start();
	}
	
	public void setNextRun(long update) {
		mNextRun = update;
	}

	public void cancelNextRun() {
		mNextRun = -1;
	}
	
	public void scheduler() {
		while (runScheduler) {
			if (mNextRun >= 0 && System.currentTimeMillis() - mNextRun >= 0) {
				if (mRunnable != null) {
					mThread = new Thread(mRunnable);
					mThread.start();
				}
				
				mNextRun = -1;
			} else {
				SystemClock.sleep(200);
			}
		}
	}
	
	public void destroy() {
		runScheduler = false;
		if (mSchedulerThread != null) {
			try {
				mSchedulerThread.join();
			} catch (InterruptedException e) {
			}
			
			mSchedulerThread = null;
		}
		
		if (mThread != null) {
			try {
				mThread.join();
			} catch (InterruptedException e) {
				
			}
			
			mThread = null;
		}
		
		mScheduler = null;
		mRunnable = null;
	}
}
